<?php

namespace app\common\model;

use app\admin\model\xshop\OrderProducts;
use think\Exception;
use think\Model;


class Orders extends Model
{
    // 表名
    protected $name = 'orders';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = false;
    public $statuArr = [
        0 => '待支付',
        1 => '支付成功',
        2 => '已退款',
        3 => '佣金已支付',
    ];
    public $checkArr = [
        0 => '待提现',
        1 => '待审核',
        2 => '已付款',
        3 => '已驳回',
    ];
    // 追加属性
    protected $append = [
        'paytime_text',
        'check_text',
        //'pay_text',
    ];


//    public function getStatusTextAttr($value, $data)
//    {
//        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
//        return isset($this->statuArr[$value]) ? $this->statuArr[$value] : '未支付';
//    }

    public function getCheckTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['check_status']) ? $data['check_status'] : '');
        $value=intval($value);
        return isset($this->checkArr[$value]) ? $this->checkArr[$value] : '--';
    }

//    public function getPayTextAttr($value, $data)
//    {
//
//        $value = $value ? $value : (isset($data['check_status']) ? $data['check_status'] : '');
//        return isset($this->statuArr[$value]) ? $this->statuArr[$value] : '-';
//    }

    /**
     * 获取支付信息
     * @$orderRow
     * pay_way 支付方式
     * pay_no 支付编号
     * title 订单名称
     * pay_price 支付金额
     */
    public function getPayinfo($orderRow)
    {
        //前往支付了
        $pay_type = isset($orderRow['pay_way']) ? $orderRow['pay_way'] : 'wechat';
        $domain = request()->domain();
        $notify = $domain . '/api/callback/notify/paytype/' . $pay_type;//异步回调地址
        $return = $domain . '/api/callback/returnx/paytype/' . $pay_type;//同步回调地址
        $params = [
            'amount' => $orderRow['pay_price'],
            'orderid' => $orderRow['pay_no'],
            'type' => $pay_type,
            'title' => $orderRow['title'],
            'notifyurl' => $notify,
            'returnurl' => $return,
            'method' => "miniapp",
            'openid' => $orderRow['openid'],
        ];
        try {
            $result = [];
            $payinfo = \addons\epay\library\Service::submitOrder($params);//微信扫码支付

            return is_array($payinfo) ? $payinfo : json_decode($payinfo, true);
        } catch (Exception $exception) {
            throw new \think\Exception($exception->getMessage(), 500);
        } catch (\Yansongda\Pay\Exceptions\Exception $exception) {
            throw new \think\Exception($exception->getMessage(), 500);
        }
        return $result;

    }

    public function orderNum($perfix = '')
    {
        $yearCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T');
        $year = date('Y');
        $number = $year . strtoupper(dechex(date('m'))) . date('d')
            . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $perfix . $number;
    }

    public function searchList($map, $filed = "*", $per_page = 14, $mapOr = [])
    {
        return $this->where($map)->whereOr($mapOr)
            ->with(['service', 'user', 'driver'])
            ->order("orders.id", 'desc')
            //->field($filed)
            ->paginate($per_page)->each(function ($item) {
                $item->hidden(['password', 'salt']);
                $item->getRelation('service')->visible(['service_name', 'mobile', 'avatar']);
                $item->getRelation('user')->visible(['nickname', 'mobile', 'avatar']);
                $item->getRelation('driver')->visible(['nickname', 'mobile', 'avatar']);
                if ($item['cancel_reason'] == '已完结(收款码)') {
                    $item['cancel_reason'] = '已完成';
                }
            });
    }

//    public function products()
//    {
//        return $this->hasOne(OrderProducts::class, 'order_id', 'id')->field('order_id,title,image,skuinfo,productinfo,attributes,title');
//    }

//    public function getImageDomainAttr($value, $data)
//    {
//        $value = isset($data['image']) ? $data['image'] : null;
//        if (!empty($value)) {
//            $domain = \request()->domain();
//            return $domain . $data['image'];
//        }
//        return '';
//    }

    public function service()
    {
        return $this->belongsTo(User::class, 'service_id', 'id')->setEagerlyType(0);
    }

    public function initStepinfo()
    {
        return
            [
                ['step' => 1, 'name' => '用户下单', 'date' => ''],
                ['step' => 2, 'name' => '司机出发', 'date' => ''],
                ['step' => 3, 'name' => '生成支付订单', 'date' => ''],
                ['step' => 4, 'name' => '订单完成', 'date' => '']
            ];
    }

    public function orderNums($uid, $filed = 'uid')
    {
        $delivered = $this->where(['assign_status' => 1, $filed => $uid])->count('id');
        $progress = $this->where(['assign_status' => 2, $filed => $uid])->count('id');
        $overed = $this->where(['assign_status' => 3, $filed => $uid])->count('id');
        $cancel = $this->where(['assign_status' => 4, $filed => $uid])->count('id');
        return [
            'delivered' => ['value' => $delivered, 'name' => '待派送'],
            'progress' => ['value' => $progress, 'name' => '进行中'],
            'overed' => ['value' => $overed, 'name' => '已完成'],
            'cancel' => ['value' => $cancel, 'name' => '已取消']
        ];
    }
}
